<template>
  <div v-infinite-scroll="load" :infinite-scroll-disabled="!morePhotos">
    <el-affix :offset="0" :z-index="10">
      <div class="top">
        <BackTo class="backto" :size="30" />
        <span class="tulin tulin-upload" @click="dialogTableVisible1=!dialogTableVisible1"></span>
        <div class="col-width"></div>
        <span v-show="photoList.length>0?photoList[0].userId==userId:false" class="tulin tulin-edit"
          @click="edit"></span>
        <div class="col-width"></div>
        <span class="tulin tulin-more" @click="toAlbumVo"></span>
        <div class="col-width"></div>
      </div>
    </el-affix>
    <!-- <el-affix :offset="0" :z-index="10">
      <div class="top">
        <BackTo class="backto" :size="30" />
        <el-dropdown trigger="click" size="large">
          <el-icon :size="30">
            <plus />
          </el-icon>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="dialogTableVisible1=!dialogTableVisible1">上传图片
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        &nbsp;
        <el-icon :size="30" @click="edit">
          <edit />
        </el-icon>
        &nbsp;
        <el-icon :size="30" @click="toAlbumVo">
          <setting />
        </el-icon>
      </div>
    </el-affix> -->
    <!-- -------------------图片集合----------------------------- -->
    <photo-provider @indexChange="indexChange" @visibleChange="visibleChange" class="view">
      <photo-consumer :src="minioUrl+photo.oosKey" v-for="photo in photoList" :key="photo"
        class="view-box" :download-name="photo.oosKey">
        <div class="view-box-item">
          <!-- 选择按钮 -->
          <div :class="className" @click.stop="checkChange($event,photo.id)">
          </div>
          <el-image :src="minioUrl+photo.oosKey" fit="cover" style="width:100%;height:100%" />
        </div>
      </photo-consumer>
    </photo-provider>
    <!-- 单图片更多操作 -->
    <div class="image-info" v-show="infoShow">
      <el-card body-style="padding:10px">
        <!-- <el-icon class="edit-icon" :size="20">
          <Rank />
        </el-icon> -->
        <el-icon class="edit-icon" :size="20" @click="downloadDialog = true">
          <Download />
        </el-icon>
        <el-icon class="edit-icon" :size="20" @click="shareDialog = true">
          <Share />
        </el-icon>
        <el-icon class="edit-icon" :size="20" @click="deleteById">
          <delete />
        </el-icon>
        <el-icon class="edit-icon" :size="20" @click="showPhotoInfo(currentPhoto.id)">
          <MoreFilled />
        </el-icon>
      </el-card>
    </div>
    <!-- 编辑操作 -->
    <div class="image-info" v-show="editShow">
      <el-card body-style="padding:10px">
        <el-icon class="edit-icon" :size="20" @click="checkAll" v-show="!isCheckAll">
          <CircleCheck />
        </el-icon>
        <el-icon class="edit-icon" :size="20" @click="checkAll" v-show="isCheckAll">
          <CircleCheckFilled />
        </el-icon>
        <el-icon class="edit-icon" :size="20">
          <Rank />
        </el-icon>
        <el-icon class="edit-icon" :size="20">
          <Download />
        </el-icon>
        <el-icon class="edit-icon" :size="20">
          <Share />
        </el-icon>
        <el-icon class="edit-icon" :size="20" @click="deleteByIds">
          <delete />
        </el-icon>
      </el-card>
    </div>
    <!-- 上传 -->
    <el-dialog v-model="dialogTableVisible1" title="上传图片" :center="true">
      <el-checkbox v-model="isDetect" label="智能分类" size="large" />
      <el-upload action="string" list-type="text" :http-request="UploadImage"
        :on-preview="handlePictureCardPreview" :on-remove="handleRemove" multiple="true">
        <el-icon :size="30">
          <Plus />
        </el-icon>
      </el-upload>
    </el-dialog>
    <div v-loading="loading"></div>
  </div>
  <!-- 图片分享 -->
  <el-dialog v-model="shareDialog" title="分享图片" :center="true">
    <input id="shareLink" type="text" value="111" />
    {{minioUrl+currentPhoto.oosKey}}<el-button type="primary" @click="copyShareLink">复制链接
    </el-button>
  </el-dialog>
  <!-- 图片下载 -->
  <el-dialog v-model="downloadDialog" title="下载" :center="true">
    <el-button @click="downloadFile(minioUrl+currentPhoto.oosKey)" type="primary">原
      图</el-button>&nbsp;&nbsp;{{sizeFormatUtil(currentPhoto.size)}}
  </el-dialog>
  <!-- 图片详情 -->
  <el-drawer v-model="showPhotoInfoView" title="图片详情" :with-header="false" direction="ttb"
    size="40%">
    <div>所属相册：{{photoInfo.album.name}}
      <el-tag class="ml-2" type="info">
        {{photoInfo.album.permission==0?"私有相册":photoInfo.album.permission==1?"全部可见":"共享相册"}}
      </el-tag>
    </div>
    <div class="row-line"></div>
    <div>
      图片名称：{{photoInfo.photo.oosKey.substring(photoInfo.photo.oosKey.lastIndexOf("/")+1,photoInfo.photo.oosKey.length)}}
    </div>
    <div class="row-line"></div>
    <div>上传时间：{{dateFormatUtil(photoInfo.photo.createTime)}}</div>
    <div class="row-line"></div>
    <div>更新时间：{{dateFormatUtil(photoInfo.album.updateTime)}}</div>
    <div class="row-line"></div>
    <div>大小：{{sizeFormatUtil(photoInfo.photo.size)}}</div>
    <div class="row-line"></div>
    <div>备注：{{photoInfo.photo.remark}}</div>
    <div class="row-line"></div>
    <div class="row-line"></div>
  </el-drawer>
</template>

<script>
import { ElMessage } from 'element-plus';
import { minioUrl } from "@/base/index";
import { copyText, sizeFormat, userId, dateFormat } from "../../utils/index";
export default {
  name: 'GPhotoShare',
  data () {
    return {
      dialogTableVisible1: false,
      morePhotos: true,
      loading: false,
      minioUrl: minioUrl,
      pageNum: 1,
      albumId: 0,
      photoList: [],
      currentPhoto: {},
      imageIndex: 0,//当前图片索引
      infoShow: false,
      editShow: false,
      checkList: [],
      className: "",
      isCheckAll: false,
      isDetect: false,
      downloadDialog: false,
      shareDialog: false,
      showPhotoInfoView: false,
      photoInfo: {},
    }
  },
  mounted () {
    this.albumId = this.$route.params.albumId;
  },
  methods: {
    UploadImage (data) {
      console.log(data);
      var forms = new FormData();
      forms.append("albumId", this.albumId);
      forms.append("file", data.file);
      forms.append("isDetect", this.isDetect);
      this.$axios({
        method: 'post',
        url: '/album/share/uploadphoto',
        data: forms,
        onUploadProgress: progressEvent => {
          const complete = parseInt(
            ((progressEvent.loaded / progressEvent.total) * 100) | 0,
            10
          )
          // 重点二：onProgress()方法需要以上方接收的形参来调用
          // 这个方法有一个参数"percent"，给他进度值 complete 即可
          data.onProgress({ percent: complete })
        }
      }).then((res) => {
        console.log(res);
        if (res.flag) {
          data.onSuccess();
          this.photoList.unshift(res.data);
        } else {
          data.onError();
        }
      })
    },
    getPhotos (albumId, pageNum, pageSize) {
      this.loading = true;
      this.$axios.get("/album/share/" + albumId + "/" + pageNum + "/" + pageSize + "").then((res) => {
        if (res.flag) {
          console.log("PhotoShare.vue->getPhotos", res);

          if (res.data.length < 1) {
            this.morePhotos = false
          } else {
            for (var key in res.data) {
              this.photoList.push(res.data[key]);
            }
          }
        } else {
          this.morePhotos = false;
          if (res.data == "noauto") {
            //没有查找权限
          } else {
            //跳转到添加共享相册使用者页面
            this.$router.push("/addshareuser/" + albumId);
          }

        }
        this.loading = false;
      })
    },
    deleteById () {
      if (this.currentPhoto != null && this.currentPhoto.id != null) {
        this.$axios.delete("photo/1/" + userId + "/" + this.currentPhoto.id).then((res) => {
          if (res.flag) {
            ElMessage({
              message: res.msg,
              grouping: true,
              type: 'success',
              duration: 2000,
            })
            const deleteId = this.currentPhoto.id
            this.photoList = this.photoList.filter(function (item) {
              return item.id != deleteId;
            });
            this.currentPhoto = this.photoList[this.imageIndex];
            this.showPhotoInfoView = false;
          }
        })
      }
    },
    deleteByIds () {
      if (this.checkList.length > 0) {
        this.$axios.delete("photo/batch/1/" + this.checkList).then((res) => {
          if (res.flag) {
            console.log(res);
            ElMessage({
              message: res.msg,
              grouping: true,
              type: 'success',
              duration: 2000,
            })
            const deleteIds = this.checkList;
            for (const key in deleteIds) {
              console.log(deleteIds[key]);
              this.photoList = this.photoList.filter(function (item) {
                return item.id != deleteIds[key];
              });
            }
            this.checkList = [];
          }
        })
      }
    },
    //查看图片详情
    showPhotoInfo (id) {
      console.log(id);
      this.showPhotoInfoView = !this.showPhotoInfoView;
      if (this.showPhotoInfoView) {
        this.$axios.get("/photo/info/" + id).then(res => {
          if (res.flag) {
            this.photoInfo = res.data;
          }
        })
      }
    },
    //预览改变触发
    indexChange (e) {
      console.log("Photo=>ChangeImage()", e);
      this.imageIndex = e.index.value;
      //如果预览时快到头了就加载图片
      if (e.index.value + 10 > e.items.value.length && this.morePhotos) {
        this.load();
      }
      //载入当前操作的图片信息
      this.currentPhoto = this.photoList[e.index.value];
    },
    visibleChange (e) {
      this.imageIndex = e.index.value;
      //如果预览时快到头了就加载图片
      if (e.index.value + 10 > e.items.value.length && this.morePhotos) {
        this.load();
      }
      //载入当前操作的图片信息
      this.currentPhoto = this.photoList[e.index.value];
      this.infoShow = !this.infoShow;
    },
    //编辑
    edit () {
      this.editShow = !this.editShow;
      this.isCheckAll = false;
      if (this.editShow) {
        this.className = "chose";
      } else {
        this.className = "";
        this.checkList = [];
      }
    },
    //全选
    checkAll () {
      this.isCheckAll = !this.isCheckAll;
      if (this.isCheckAll) {
        this.className = "chose-active";
        this.checkList = [];
        for (const key in this.photoList) {
          this.checkList.push(this.photoList[key].id);
        }
      } else {
        this.className = "chose";
        this.checkList = [];
      }
    },
    //选择变化
    checkChange (e, id) {
      if (e.target.getAttribute('class') == "chose-active") {
        //取消选择
        e.target.setAttribute('class', 'chose');
        //去掉id
        this.checkList = this.checkList.filter((item) => {
          return item != id;
        })
      } else {
        //选择将选择的id加入checklist
        e.target.setAttribute('class', 'chose-active');
        this.checkList.push(id);
      }
    },
    //下载图片
    downloadFile (url) {
      //下载文件
      console.log(url)
      let a = document.createElement("a");
      a.setAttribute("href", url);
      a.setAttribute("download", 'download');
      a.setAttribute("target", "_blank");
      let clickEvent = document.createEvent("MouseEvents");
      clickEvent.initEvent("click", true, true);
      a.dispatchEvent(clickEvent);
    },
    copyShareLink () {
      var content = document.getElementById('shareLink');
      copyText(content, this.minioUrl + this.currentPhoto.oosKey);
    },
    sizeFormatUtil (size) {
      return sizeFormat(size);
    },
    load () {
      this.getPhotos(this.albumId, this.pageNum++, 10);
    },
    toAlbumVo () {
      this.$router.push("/album/vo/" + this.albumId);
    },
    dateFormatUtil (date) {
      return dateFormat(date, 1);
    }
  },
}
</script>

<style scoped>
@media (min-width: 0px) {
  .view-box {
    width: 50%;
    height: 100px;
  }
  .view-box-item {
    height: 100px;
  }
}
@media (min-width: 280px) {
  .view-box {
    width: 25%;
  }
  .view-box-item {
    height: 100px;
    padding-left: 2px;
    padding-right: 2px;
  }
}
@media (min-width: 750px) {
  .view-box {
    width: 20%;
  }
  .view-box-item {
    height: 150px;
  }
}
@media (min-width: 1080px) {
  .view-box {
    width: 10%;
  }
  .view-box-item {
    height: 100px;
  }
}
.top {
  width: 100%;
  text-align: right;
  background-color: var(--primary);
  z-index: 10;
}
.el-image-error {
  height: 100%;
  line-height: 200px;
  color: gray;
}
.image-info {
  z-index: 10000;
  position: fixed;
  /* width: 200px; */
  height: 40px;
  /* background-color: blue; */
  bottom: 80px;
  left: calc(50% - 82px);
}
.view-box-item {
  position: relative;
}
.edit-icon {
  margin-left: 13px;
}
.edit-icon:last-child {
  margin-right: 13px;
}
.chose,
.chose-active {
  position: absolute;
  width: calc(100% - 7px);
  height: calc(100% - 4px);
  z-index: 1;
  cursor: pointer;
}
/* 选择时的小点 */
.chose::after {
  content: '';
  display: block;
  position: absolute;
  top: 5px;
  right: 5px;
  background-color: white;
  width: 15px;
  height: 15px;
  border-radius: 50%;
}
.chose-active {
  background-color: rgba(255, 255, 255, 0.5);
  border: 2px solid var(--primary);
}
.chose-active::after {
  content: '';
  display: block;
  position: absolute;
  top: 5px;
  right: 5px;
  /* background-color: var(--primary); */
  background: url('../../assets/imge/inco/check.png');
  background-position: center;
  background-repeat: no-repeat;
  vertical-align: middle;
  background-size: 20px 20px;
  width: 15px;
  height: 15px;
  border-radius: 50%;
}
.backto {
  position: absolute;
  left: 5px;
}
#shareLink {
  position: fixed;
  left: 10000px;
}
</style>